package com.powernode.ssm.utils;

import cn.hutool.core.lang.Assert;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;

import com.powernode.ssm.pojo.po.H5UserinfoPo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class ImportAndExportUtils {
    private static final Logger log = LoggerFactory.getLogger(ImportAndExportUtils.class);

    public static String exportEasyExcelWithTemplate(String templatePath, String outputFilePath, List<?> data) {

        ExcelWriter excelWriter = EasyExcel.write(outputFilePath).withTemplate(new File(templatePath)).build();

        WriteSheet writeSheet = EasyExcel.writerSheet(0).build();

        excelWriter.fill(data, writeSheet);

        excelWriter.finish();

        return outputFilePath;

    }

    public static void export(HttpServletResponse response, H5UserinfoPo h5UserinfoPo, boolean encrypt, String pathAndFilename, String exportType) {
        //增加判断是否加密，可选
        realExport(pathAndFilename,response,exportType);
    }

    public static void realExport(String pathAndFilename, HttpServletResponse response, String exportType) {
        String srcFileName = pathAndFilename + exportType;

        int i = srcFileName.lastIndexOf("/");
        int j = srcFileName.lastIndexOf(".");
        String substring = srcFileName.substring(i + 1, j);
        String filename = substring + exportType;
        downLoadFile(srcFileName, filename, response);

        File file = new File(srcFileName);

        if (forceDelete(file)){
            log.info("删除服务器中的{}文件成功",srcFileName);
        }else {
            log.info("删除服务器中的{}文件失败",srcFileName);
        }
    }

    private static boolean forceDelete(File file) {
        Assert.notNull(file);
        boolean result = false;
        int tryCount = 0;
        while (!result&&tryCount ++ <10){
            System.gc();
            result  = file.delete();
        }
        return result;
    }

    private static void downLoadFile(String path, String filename, HttpServletResponse response) {
        Assert.notEmpty(path);
        Assert.notEmpty(filename);

        File file = new File(path);
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            String nameSuffix = filename.substring(filename.lastIndexOf(".") + 1);
            if ("pdf".equals(nameSuffix)) {
                response.setContentType("application/pdf");
            } else if ("csv".equals(nameSuffix)) {
                response.setContentType("text/csv");
            } else {
                log.info("非pdf文件和csv文件");
            }
            outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
